package spingmvcstudent.Dao;

import spingmvcstudent.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.List;
@Component(value = "userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
     JdbcTemplate jdbcTemplate;

    @Override
    public List<User> getAllUser() {
        String sql = "select * from user";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> users = jdbcTemplate.query(sql, rowMapper);
        return users;
    }

    @Override
    public int addUser(User user) {



            String sql = "insert into user(username,password) values(?,?)";
        int i = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
        return i;


    }

    @Override
    public int deleteUser(Integer id) {
        String sql = "delete from user where id=?";
        int i = jdbcTemplate.update(sql, id);
        return i;
    }

    @Override
    public List<User> findByName(String username) {
        String sql = "select * from user where username = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> users = jdbcTemplate.query(sql, rowMapper,username);
        return users;
    }

    @Override
    public List<User> findById(Integer id) {
        String sql = "select * from user where id = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> users = jdbcTemplate.query(sql, rowMapper,id);
        return users;
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set username=?,password=? where id=?";
        int i = jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getId());
        return i;
    }

    @Override
    public List<User> findByIdAandName(Integer id, String username) {
        String sql = "select * from user where id != ? and username = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> users = jdbcTemplate.query(sql, rowMapper,id,username);
        return users;
    }

    @Override
    public List<User> findByNameAndPassword(String username, String password) {
        String sql = "select * from user where username = ? and password = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> users = jdbcTemplate.query(sql, rowMapper,username,password);
        return users;
    }
}
